package com.hupu.jrs.util

import android.content.Context
import android.os.Environment
import java.io.File

/**
 * Created by sll on 2015/5/16.
 */
object CacheUtil {

    fun getCacheSize(context: Context): String {
        // 计算缓存大小
        var fileSize: Long = 0
        var cacheSize = "0KB"
        val filesDir = context.filesDir
        val cacheDir = context.cacheDir
        val ExternalCacheDir = context.externalCacheDir

        fileSize += FormatUtil.getDirSize(filesDir)
        fileSize += FormatUtil.getDirSize(cacheDir)
        fileSize += FormatUtil.getDirSize(ExternalCacheDir)
        if (fileSize > 0) cacheSize = FormatUtil.formatFileSize(fileSize)
        return cacheSize
    }

    fun cleanApplicationCache(context: Context) {
        cleanInternalCache(context)
        cleanExternalCache(context)
        cleanFiles(context)
    }

    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
     */
    fun cleanInternalCache(context: Context) {
        deleteFilesByDirectory(context.cacheDir)
    }

    /**
     * 清除/data/data/com.xxx.xxx/files下的内容
     */
    fun cleanFiles(context: Context) {
        deleteFilesByDirectory(context.filesDir)
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     */
    fun cleanExternalCache(context: Context) {
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            deleteFilesByDirectory(context.externalCacheDir)
        }
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理
     */
    private fun deleteFilesByDirectory(directory: File?) {
        if (directory != null && directory.exists() && directory.isDirectory) {
            for (item in directory.listFiles()) {
                if (item.isDirectory) {
                    deleteFilesByDirectory(item)
                }
                item.delete()
            }
            directory.delete()
        }
    }
}
